package main

import (
	"fmt"
	"strconv"
	"time"
	"zinx_websokect_poker/zinx/ziface"
	"zinx_websokect_poker/zinx/znet"
	"zinx_websokect_poker/zinx_app/poker_game/api"
	"zinx_websokect_poker/zinx_app/poker_game/core"
	"zinx_websokect_poker/zinx_app/poker_game/log"
)

func DoConnectionBegin(conn ziface.IWSConnection)  {
	fmt.Println("DoConnecionBegin is Called ... ")
	//创建一个玩家
	player := core.NewPlayer(conn)
	core.NewOccupant(player,conn)
	//=============在连接创建之后===========
	conn.SetProperty("Pid", player.Pid)
	player.Status = core.Idle
	//===================================================
	log.Info("ConnectionBegin","建立连接ID" + strconv.Itoa(int(conn.GetConnID())))
	// 连接创建后30秒，检查玩家的OutId，没有则断开连接。
	time.AfterFunc(time.Second * 30, func() {
		if oid,_ := conn.GetProperty("OutId"); oid == nil {
			fmt.Println("玩家数据异常，断开连接！")
			conn.Stop()
		}
	})

}

//连接断开的时候执行
func DoConnectionLost(conn ziface.IWSConnection) {
	p,_ := conn.GetProperty("Pid")
	if p != nil {
		pid := p.(uint32)
		o := core.OccupantMgrObj.GetOccupantByPid(pid)
		//设置离线
		if o != nil {
			o.SetOffline()
			if o.RoomID == "" {
				//玩家在大厅中掉线。
				//移除连接所属的旧的玩家数据
				core.OccupantMgrObj.RemoveOccupantByPid(pid)
				core.PlayerMgrObj.RemovePlayerByPid(pid)
			}
		}
	}
	log.Info("ConnectionLost","断开连接ID" + strconv.Itoa(int(conn.GetConnID())))

	fmt.Println("DoConneciotnLost is Called ... ")
}

func main() {
	//创建一个server句柄
	s := znet.NewServer()

	s.SetOnConnStart(DoConnectionBegin)
	s.SetOnConnStop(DoConnectionLost)

	//配置路由 在api里新增路由根据不同的msgID 处理不同的Msg

	//创建房间操作
	s.AddRouter(1, &api.CreateRoomApi{})
	//进房
	s.AddRouter(2, &api.GoRoomApi{})
	//处理玩家信息
	s.AddRouter(3, &api.BindInfoApi{})
	//
	s.AddRouter(6, &api.GetRoomInfoApi{})
	//坐下
	s.AddRouter(50, &api.SitDownApi{})
	//开始游戏
	s.AddRouter(51, &api.GameApi{})
	//下注
	s.AddRouter(52, &api.SetActionApi{})
	//s.AddRouter(53, &api.SetActionResponseApi{})

	//s.AddRouter(53, &api.ReqRound2Api{})
	//s.AddRouter(54, &api.ReqRound3Api{})
	//s.AddRouter(55, &api.ReqRound4Api{})
	//s.AddRouter(56, &api.ReqResultApi{})

	//
	s.AddRouter(58, &api.StandUpApi{})
	//
	s.AddRouter(59, &api.LeaveRoomApi{})

	s.AddRouter(62, &api.ChatApi{})

	//开启服务
	s.Serve()
}
